package com.dnjn.happiness.survey.controller.admin;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.survey.domain.Answer;
import com.dnjn.happiness.survey.domain.Survey;
import com.dnjn.happiness.survey.domain.SurveyIntervalScore;
import com.dnjn.happiness.survey.domain.SurveyRecord;
import com.dnjn.happiness.survey.domain.vo.SurveyIntervalScoreVO;
import com.dnjn.happiness.survey.service.IAnswerService;
import com.dnjn.happiness.survey.service.ISurveyIntervalScoreService;
import com.dnjn.happiness.survey.service.ISurveyRecordService;
import com.dnjn.happiness.survey.service.ISurveyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 答案表Controller
 *
 * @author happiness
 * @date 2023-10-24
 */
@Tag(name = "admin survey answer 答案表", description = "答案表")
@RestController
@RequestMapping("/admin/answer")
public class AdminAnswerController extends BaseController {
    @Autowired
    private IAnswerService answerService;

    @Autowired
    private ISurveyRecordService recordService;

    @Autowired
    private ISurveyService surveyService;

    @Autowired
    private ISurveyIntervalScoreService surveyIntervalScoreService;

    @Log(title = "答案表", businessType = BusinessType.INSERT)
    @PostMapping("/goToAnswer1")
    @RequiresPermissions("survey:answer:add")
    @Operation(summary = "后台-去答题- userId(答题人)-surveyId(问卷id)-questionId(题目id)-answer(答案)-answerRight(正确答案)")
    public AjaxResult goToAnswer1(@RequestBody List<Answer> domain) {
        answerService.goToAnswer(domain);
        return success();
    }

    @Log(title = "答案表", businessType = BusinessType.INSERT)
    @PostMapping("/goToAnswer")
    @Operation(summary = "小程序-去答题- userId(答题人)-surveyId(问卷id)-questionId(题目id)-answer(答案)-answerRight(正确答案)")
    public AjaxResult goToAnswer(@RequestBody List<Answer> domain) {
        answerService.goToAnswer(domain);
        return success();
    }

    @Log(title = "答案表", businessType = BusinessType.INSERT)
    @PostMapping("/selectRecordList1")
    @Operation(summary = "后台-我的问卷-根据问卷id查看答题列表")
    @RequiresPermissions("survey:answer:query")

    public AjaxResult selectRecordList1(@Parameter(description = "问卷id") Long surveyId, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<SurveyRecord> list = answerService.selectRecordList1(surveyId, Page.of(current, size).addOrder(OrderItem.desc("survey_record_id")));

        return success(list);
    }

    @Log(title = "答案表", businessType = BusinessType.INSERT)
    @PostMapping("/selectRecordList")
    @Operation(summary = "小程序-我的问卷-根据问卷id查看答题列表")

    public AjaxResult selectRecordList(@Parameter(description = "问卷id") Long surveyId, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<SurveyRecord> list = answerService.selectRecordList1(surveyId, Page.of(current, size).addOrder(OrderItem.desc("survey_record_id")));

        return success(list);
    }

    @Log(title = "答案表", businessType = BusinessType.INSERT)
    @PostMapping("/selectAnswerList")
    @Operation(summary = "小程序-答题详情--传参  surveyId(问卷id) 和 userId(答题者) ", description = "必填:surveyId(问卷id) 和 userId(答题者)")
    public AjaxResult selectAnswer(@RequestBody SurveyRecord domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<Answer> list = answerService.selectAnswerList(domain, Page.of(current, size));

        return success(list);
    }

    //答题详情-数据图
    @Operation(summary = "答题详情-数据图")
    @GetMapping("/answerGraphsDetailBack/{surveyId}")
    @RequiresPermissions("survey:answer:query")
    public AjaxResult answerGraphsDetailBack(@PathVariable Long surveyId) {
        String participatedCountResult = "0";
        String unParticipatedCountResult = "0";
        List<SurveyRecord> surveyRecordList = recordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).eq(SurveyRecord::getDeleted, "0").list();
        int participatedCount = 0;
        int unParticipatedCount = 0;
        if (null != surveyRecordList && surveyRecordList.size() > 0) {
            int totalSize = surveyRecordList.size();
            for (SurveyRecord item : surveyRecordList) {
                if ("Y".equals(item.getRecordStatus())) {
                    participatedCount++;
                }
                if ("N".equals(item.getRecordStatus())) {
                    unParticipatedCount++;
                }
            }
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(2);
            participatedCountResult = format.format((float) participatedCount / (float) totalSize * 100);
            unParticipatedCountResult = format.format((float) unParticipatedCount / (float) totalSize * 100);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("participatedCountResult", participatedCountResult + "%");
        map.put("unParticipatedCountResult", unParticipatedCountResult + "%");
        map.put("participatedCount", participatedCount);
        map.put("unParticipatedCount", unParticipatedCount);
        map.put("headCount", surveyRecordList.size());

        return AjaxResult.success(map);
    }


    //答题详情-区间展示
    @Operation(summary = "答题详情-区间展示")
    @GetMapping("/answerIntervalDetailBack/{surveyId}")
    @RequiresPermissions("survey:answer:query")
    public AjaxResult answerIntervalDetailBack(@PathVariable Long surveyId) {
        HashMap<String, Object> map = new HashMap<>();
        Survey survey = surveyService.getById(surveyId);
        List<SurveyIntervalScore> intervalScoreList = surveyIntervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyId).list();
        List<SurveyRecord> surveyRecordList = recordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).eq(SurveyRecord::getDeleted, "0").list();
        List<SurveyIntervalScoreVO> voList = getVoList(survey, intervalScoreList, surveyRecordList);
        return AjaxResult.success(voList);

    }


    //答题详情-数据图
    @Operation(summary = "wx答题详情-数据图")
    @GetMapping("/answerGraphsDetail/{surveyId}")
    public AjaxResult answerGraphsDetail(@PathVariable Long surveyId) {
        String participatedCountResult = "0";
        String unParticipatedCountResult = "0";
        List<SurveyRecord> surveyRecordList = recordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).eq(SurveyRecord::getDeleted, "0").list();
        int participatedCount = 0;
        int unParticipatedCount = 0;
        if (null != surveyRecordList && surveyRecordList.size() > 0) {
            int totalSize = surveyRecordList.size();
            for (SurveyRecord item : surveyRecordList) {
                if ("Y".equals(item.getRecordStatus())) {
                    participatedCount++;
                }
                if ("N".equals(item.getRecordStatus())) {
                    unParticipatedCount++;
                }
            }
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(2);
            participatedCountResult = format.format((float) participatedCount / (float) totalSize * 100);
            unParticipatedCountResult = format.format((float) unParticipatedCount / (float) totalSize * 100);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("participatedCountResult", participatedCountResult + "%");
        map.put("unParticipatedCountResult", unParticipatedCountResult + "%");
        map.put("participatedCount", participatedCount);
        map.put("unParticipatedCount", unParticipatedCount);
        map.put("headCount", surveyRecordList.size());

        return AjaxResult.success(map);
    }


    //答题详情-区间展示
    @Operation(summary = "wx答题详情-区间展示")
    @GetMapping("/answerIntervalDetail/{surveyId}")
    public AjaxResult answerIntervalDetail(@PathVariable Long surveyId) {
        HashMap<String, Object> map = new HashMap<>();
        Survey survey = surveyService.getById(surveyId);
        List<SurveyIntervalScore> intervalScoreList = surveyIntervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyId).list();
        List<SurveyRecord> surveyRecordList = recordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).eq(SurveyRecord::getDeleted, "0").list();
        List<SurveyIntervalScoreVO> voList = getVoList(survey, intervalScoreList, surveyRecordList);
        return AjaxResult.success(voList);

    }

    private List<SurveyIntervalScoreVO> getVoList(Survey survey, List<SurveyIntervalScore> intervalScoreList, List<SurveyRecord> surveyRecordList) {
        List<SurveyIntervalScoreVO> voList = new ArrayList<>();
        if (null == surveyRecordList || surveyRecordList.size() == 0) {
            if (null == intervalScoreList || intervalScoreList.size() == 0) {
                return voList;
            } else {
                setRatio(intervalScoreList, voList);
                return voList;
            }
        } else {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(2);
            NumberFormat format1 = NumberFormat.getInstance();
            format1.setMaximumFractionDigits(0);
            format1.setRoundingMode(RoundingMode.HALF_UP);
            int totalSize = surveyRecordList.size();
            if (null == intervalScoreList || intervalScoreList.size() == 0) {
                return voList;
            } else {
                for (SurveyIntervalScore intervalScore : intervalScoreList) {
                    SurveyIntervalScoreVO vo = new SurveyIntervalScoreVO();
                    BeanUtils.copyPropsIgnoreNull(intervalScore, vo);
                    int count = 0;
                    Integer startScore = vo.getStartScore();
                    Integer endScore = vo.getEndScore();
                    for (SurveyRecord surveyRecord : surveyRecordList) {
                        if (!ObjectUtils.isEmpty(surveyRecord.getSurveyScore())) {
                            if (startScore <= surveyRecord.getSurveyScore() && surveyRecord.getSurveyScore() <= endScore) {
                                count++;
                            }
                        }
                    }
                    String result = format.format((float) count / (float) totalSize * 100);
                    vo.setRatio(result + "%");
                    vo.setUserCount(count);
                    String percent = format1.format((float) count / (float) totalSize * 100);
                    vo.setPercent(Integer.parseInt(percent));
                    voList.add(vo);
                }
                return voList;
            }
        }
    }


    private List<SurveyIntervalScoreVO> quarterMethod(List<SurveyIntervalScoreVO> voList, Integer maxScore, Integer minScore) {
        if (ObjectUtils.isEmpty(maxScore) || ObjectUtils.isEmpty(minScore)) {
            return voList;
        }
        //四分法
        int interval = (maxScore - minScore) / 4;
        for (int j = 0; j < 4; j++) {
            SurveyIntervalScoreVO vo = new SurveyIntervalScoreVO();
            vo.setStartScore(minScore + (j * interval));
            vo.setEndScore(minScore + ((j + 1) * interval));
            vo.setRatio("0%");
            voList.add(vo);
        }
        return voList;
    }

    private void setRatio(List<SurveyIntervalScore> intervalScoreList, List<SurveyIntervalScoreVO> voList) {
        for (SurveyIntervalScore surveyIntervalScore : intervalScoreList) {
            SurveyIntervalScoreVO vo = new SurveyIntervalScoreVO();
            BeanUtils.copyPropsIgnoreNull(surveyIntervalScore, vo);
            vo.setRatio("0%");
            voList.add(vo);
        }
    }


}
